<template>
    <div class="auth-container">
        <!-- 公共表单容器 -->
        <a-card :title="isLogin ? '用户登录' : '用户注册'" class="auth-card">
            <a-form :model="formState" name="basic" autocomplete="off" layout="vertical" @finish="handleSubmit">
                <!-- 用户名输入 -->
                <a-form-item label="用户名" name="username" :rules="rules.username" has-feedback>
                    <a-input v-model:value="formState.username" placeholder="默认admin" />
                </a-form-item>

                <!-- 密码输入 -->
                <a-form-item label="密码" name="password" :rules="rules.password" has-feedback>
                    <a-input-password v-model:value="formState.password" placeholder="默认admin" />
                </a-form-item>

                <!-- 注册时显示确认密码 -->
                <a-form-item v-if="!isLogin" label="确认密码" name="confirmPassword" :rules="rules.confirmPassword"
                    has-feedback>
                    <a-input-password v-model:value="formState.confirmPassword" />
                </a-form-item>

                <!-- 注册时显示邮箱 -->
                <a-form-item v-if="!isLogin" label="邮箱" name="email" :rules="rules.email" has-feedback>
                    <a-input v-model:value="formState.email" />
                </a-form-item>

                <!-- 提交按钮 -->
                <a-form-item>
                    <a-button type="primary" html-type="submit" :loading="loading" block>
                        {{ isLogin ? '登录' : '立即注册' }}
                    </a-button>
                </a-form-item>

                <!-- 切换登录/注册 -->
                <div class="toggle-text">
                    {{ isLogin ? '没有账号？' : '已有账号？' }}
                    <a @click="toggleAuthMode">
                        {{ isLogin ? '立即注册' : '立即登录' }}
                    </a>
                </div>
            </a-form>
        </a-card>
    </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import { userlogin, userregiter } from '@/api/apitest';
import { useRouter } from 'vue-router';

const router = useRouter()

// 响应式状态管理
const formState = reactive({
    username: 'admin',
    password: 'admin',
    confirmPassword: '123456', // 仅注册时使用
    email: '13131@131.com'          // 仅注册时使用
});

const isLogin = ref(true); // 当前是否为登录状态
const loading = ref(false); // 提交加载状态

// 表单验证规则
const validatePass2 = async (_rule, value) => {
    if (value === '') {
        return Promise.reject('请再次输入确认密码');
    } else if (value !== formState.password) {
        return Promise.reject("两次输入密码不同，重新输入!");
    } else {
        return Promise.resolve();
    }
};
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 4, max: 16, message: '用户名长度为4-16个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 18, message: '密码长度为5-18个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, trigger: 'blur', validator: validatePass2 },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
    ]
};


// 切换登录/注册状态
const toggleAuthMode = () => {
    isLogin.value = !isLogin.value;
    // 清空确认密码和邮箱字段
    formState.confirmPassword = '';
    formState.email = '';
};

// 提交处理
const handleSubmit = async () => {
    loading.value = true;
    try {
        if (isLogin.value) {
            // 处理登录逻辑
            const result = await handleLogin();
            console.log(result.status);
            if (result.status == 'success') {
                message.success(result.message);
            } else {
                message.error(result.message)
            }
            router.push('/')//登录成功路由跳转
        } else {
            // 处理注册逻辑
            const result = await handleRegister();
            if (result.status == 'success') {
                message.success(result.message);
                toggleAuthMode(); // 注册成功后切换到登录
            } else {
                message.error(result.message)
            }
        }
    } catch (error) {
        console.log(error);
        message.error(error.message || '操作失败');
    } finally {
        loading.value = false;
    }
};

// 登录具体逻辑
const handleLogin = async () => {
    const data = await userlogin(formState.username, formState.password)
    if (data.result[0] == '登录成功') {
        localStorage.setItem('user', JSON.stringify(data.result[1][0]))
        return {
            status: 'success',
            message: `欢迎用户：${data.result[1][0].username}`
        }
    } else if (data.result[0] == '无该用户名') {
        return {
            status: 'error',
            message: `${data.result[0]}+请先注册账号`
        }
    } else if (data.result[0] == '密码错误') {
        return {
            status: 'error',
            message: `${data.result[0]}`
        }
    }

    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
};

// 注册具体逻辑
const handleRegister = async () => {
    const data = await userregiter(formState.username, formState.password, formState.email)
    if (data.result[0] == '注册成功') {
        return {
            status: 'success',
            message: `${data.result[0]}`
        }
    } else if (data.result[0] == '邮箱已存在，请更换邮箱') {
        return {
            status: 'error',
            message: `${data.result[0]}`
        }
    } else if (data.result[0] == '用户名已存在，请更换其他用户名') {
        return {
            status: 'error',
            message: `${data.result[0]}`
        }
    }

    // 这里替换为实际的注册API调用
    console.log('注册请求', {
        username: formState.username,
        password: formState.password,
        email: formState.email
    });
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
};
</script>

<style scoped>
.auth-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: #f0f2f5;
}

.auth-card {
    width: 400px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.toggle-text {
    text-align: center;
    margin-top: 16px;
    color: #666;
}

.toggle-text a {
    color: #1890ff;
}
</style>
